<template>
  <div class="declare-page">
    <!-- <Drawer
      :closable="false"
      :mask-closable="true"
      width="1200"
      v-model="drawer"
      class="declare-drawer"
      title="靶标申报审核"
    >
      <div style="position: absolute;top: 70px;left: -17px;cursor: pointer" @click="drawer = false">
        <img src="../../assets/globalIcon/closeIcon.png" alt="Close" />
      </div> -->
    <div class="search-wrapper flex-end">
      <Select filterable
        transfer
        v-model="query.checkStatus"
        placeholder="请选择申报状态"
        filterable
        clearable
        @on-change="changePage(1)"
      >
        <Option :value="0">未审核</Option>
        <Option :value="1">已通过</Option>
        <Option :value="2">未通过</Option>
        <Option :value="3">已驳回</Option>
        <Option :value="5">驳回再修改</Option>
      </Select>
      <Select filterable
        v-model="query.company"
        filterable
        clearable
        transfer
        placeholder="请选择单位"
        @on-change="changePage(1)"
      >
        <Option v-for="item in companyList" :value="item" :key="item" :title="item">{{
          item
        }}</Option>
      </Select>
      <Select filterable
        v-model="query.teamId"
        filterable
        clearable
        transfer
        placeholder="请选择团队"
        @on-change="changePage(1)"
      >
        <Option v-for="item in groupList" :value="item.id" :key="item.id" :title="item.name">{{
          item.name
        }}</Option>
      </Select>
      <Button @click="refresh"><i class="el-icon-refresh-right"/></Button>
    </div>
    <div ref="table-wrapper">
      <TableList 
        :columns="columns" 
        :data="dataList"
        :total="total"
        :size.sync="query.pageSize"
        :page.sync="query.pageIndex"
        @queryFun="queryDeclareTargetList"
        >
      </TableList>
      <!-- <Table border :columns="columns" :data="dataList"></Table> -->
    </div>
    <!-- <div class="page-wrapper" v-if="total > 0">
      <Page
        :total="total"
        :page-size="query.pageSize"
        :current="query.pageIndex"
        @on-change="changePage"
        show-total
        show-elevator
      />
    </div> -->
    <!-- </Drawer> -->
    <Modal v-model="checkModal.show" title="审核" :width="600">
      <Card dis-hover>
        <template #title>申报详情</template>
        <Form :label-width="40">
          <FormItem label="单位" style="margin-bottom:0">
            {{ checkModal.data.company }}
          </FormItem>
          <FormItem label="目标" style="margin-bottom:0">
            {{ checkModal.data.name }}
          </FormItem>
          <FormItem label="描述" style="margin-bottom:0">
            <p class="html-content target-des ql-editor" v-html="checkModal.data.description" style="margin-top: 8px;"></p>
          </FormItem>
        </Form>
      </Card>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <!-- <FormItem label="单位">
          {{ checkModal.data.company }}
        </FormItem> -->
        <!-- <FormItem label="申报描述">
          <p class="html-content" v-html="checkModal.data.description"></p>
        </FormItem> -->
        <FormItem label="结果" prop="checkStatus">
          <RadioGroup v-model="formValidate.checkStatus" @on-change="changeCheckStatus">
            <Radio :label="1">通过</Radio>
            <!-- 通过的目标不可以改成不通过，因为（通过的靶标会进行分配和提交报告等操作） -->
            <Radio :label="2" :disabled="checkModal.data.checkStatus === 1">不通过</Radio>
            <Radio :label="3">驳回</Radio>
            <!-- <Radio :label="5" disabled>驳回后再修改</Radio> -->
          </RadioGroup>
        </FormItem>
        <FormItem label="基础分" prop="basicScore" v-if="formValidate.checkStatus == 1">
          <InputNumber
            :min="0"
            v-model.trim="formValidate.basicScore"
            placeholder="基础分"
            style="width:110px"
          ></InputNumber>
        </FormItem>
        <FormItem label="审核意见" prop="opinion">
          <Input
            v-model.trim="formValidate.opinion"
            clearable
            type="textarea"
            :maxlength="1000"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="审核意见"
          ></Input>
        </FormItem>
        <FormItem
          label="驳回本目标的所有报告"
          prop="isRefuseReports"
          key="isRefuseReports"
          v-if="!checkModal.allowReject && formValidate.checkStatus == 3"
        >
          <RadioGroup v-model="formValidate.isRefuseReports">
            <Radio :label="1">是</Radio>
            <Radio :label="0">否</Radio>
          </RadioGroup>
          <p style="color:#ff9900" v-show="formValidate.isRefuseReports == 0">
            <Icon type="ios-information-circle-outline" />驳回目标申请前请先手动驳回本目标所有报告
          </p>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="checkModal.show = false">取消</Button>
        <Button type="primary" :loading="checkModal.loading" @click="checkDeclareTarget"
          >确定</Button
        >
        <!--  v-show="currentType !== 2" -->
      </div>
    </Modal>
    <Modal
      v-model="approvalInfoModal.show"
      :title="approvalInfoModal.title"
      footer-hide
      class-name="fix-height-modal"
      :width="600"
    >
      <div v-html="approvalInfoModal.content" style="font-size:14px;" class="noticeContent ql-editor"></div>
    </Modal>
    <img-view ref="imgView"></img-view>
    <!-- <img
      src="../../assets/login/loginBg.jpg"
      style="width:20px;height:20px;"
      @click="prevImg"
    /> -->
  </div>
</template>
<script>
import $ from 'jquery';
import {
  queryDeclareTargetList,
  checkDeclareTarget,
  getDeclareCompanyList
} from '@/api/drill_compete';
import { getTargetReportsStatus, rejectTargetReports } from '@/api/referee';
import { getaccessgrouplist } from '@/api/access_new';
import TableTooltip from '@/view/drill_compete/page/tableTooltip.vue';
import ImgView from './img-view';
import { getNumReg } from '@/libs/reg.js';
export default {
  name: 'DeclareTargetDrawer',
  components: { TableTooltip, ImgView },
  props: ['sceneId', 'projectId'],
  data() {
    const validateScore = (rule, value, callback) => {
      if (value !== 0 && !value) {
        callback(new Error('不能为空'));
        return;
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入整数'));
        return;
      }
      if (value < 0 || value > 100000) {
        callback(new Error('请输入0-100000的整数'));
        return;
      }
      callback();
    };
    return {
      drawer: false,
      query: {
        pageIndex: 1,
        pageSize: 12
      },
      dataList: [],
      total: 0,
      checkStatusObj: {
        0: {
          label: '未审核',
          value: '0'
        },
        1: {
          label: '已通过',
          value: '1'
        },
        2: {
          label: '未通过',
          value: '2'
        },
        3: {
          label: '已驳回',
          value: '3'
        },
        5: {
          label: '驳回再修改',
          value: '5'
        }
      },
      columns: [
        {
          title: '目标',
          key: 'name',
          // fixed: 'left',
          width: 400,
          tooltip: true
        },
        {
          title: '团队',
          key: 'teamName',
          width: 100,
          tooltip: true
        },
        {
          title: '单位',
          key: 'company',
          width: 100,
          tooltip: true
        },
        {
          title: 'IP',
          key: 'ip',
          width: 100,
          tooltip: true
        },
        {
          title: 'URL',
          key: 'url',
          width: 100,
          tooltip: true
        },
        {
          title: '状态',
          key: 'checkStatus',
          width: 100,
          tooltip: true,
          render: (h, { row: { checkStatus } }) => {
            return h('span', this.checkStatusObj[checkStatus].label);
          },
          placement: 'top-right'
        },
        {
          title: '申报时间',
          key: 'createTime',
          width: 180,
          tooltip: true
        },
        {
          title: '基础分',
          key: 'basicScore',
          width: 100,
          tooltip: true,
          render: (h, params) => {
            return h(
              'span',
              params.row.basicScore || params.row.basicScore === 0 ? params.row.basicScore : '-'
            );
          }
        },
        {
          type:'html',
          title: '描述',
          key: 'description',
          // tooltip: true,
          width: 200,
          // render: (h, params) => {
          //   let content = params.row.description;
          //   return content
          //     ? h(TableTooltip, {
          //         props: {
          //           type: 'html',
          //           content: content,
          //           tipWidth: 600
          //         }
          //       })
          //     : h('span', '-');
          // }
        },
        {
          title: '审核意见',
          key: 'opinion',
          tooltip: true,
          width: 100
        },
        {
          title: '审核人',
          key: 'modifierName',
          align: 'center',
          width: 100,
          tooltip: true
        },
        {
          title: '审核时间',
          key: 'lastUpdateTime',
          align: 'center',
          width: 180
        },
        {
          title: '操作',
          key: 'active',
          width: 100,
          // fixed: 'right',
          action: true,
          render: (h, params) => {
            return h(
              'Button',
              {
                props: {
                  type: 'info',
                  size: 'small', 
                  // disabled: params.row.checkStatus == 1 
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: async () => {
                    this.checkModal.show = true;
                    this.$refs.formValidate.resetFields();
                    let allowReject;
                    if (params.row.checkStatus == 0) {
                      this.formValidate = { ...this._formValidate };
                    } else {
                      this.formValidate = { ...params.row, isRefuseReports: 1 };
                      //不是未审核
                      allowReject = await this.getTargetReportsStatus(params.row.targetId);
                      this.checkModal.allowReject = allowReject;
                    }
                    this.checkModal.data = {...params.row};
                    $('.target-des').on('click', 'img', (e) => {
                      this.$refs.imgView.showModal(e.target);
                    });
                  }
                }
              },
              '审核'
            );
          }
        }
      ],
      groupList: [],
      companyList: [],
      checkModal: {
        show: false,
        data: { id: '', company: '', description: '' },
        loading: false
      },
      formValidate: {
        checkStatus: 1,
        basicScore: 0,
        opinion: '',
        isRefuseReports: 1
      },
      ruleValidate: {
        checkStatus: [{ required: true, type: 'number', trigger: 'change' }],
        basicScore: [
          {
            required: true,
            type: 'number',
            min: 0,
            max: 100000,
            validator: validateScore,
            trigger: 'change,blur'
          }
        ],
        opinion: [
          { required: true, min: 1, message: '请填写审核意见', trigger: 'change' }
          // { type: 'string', min: 20, message: '审核意见最少输入20个字符', trigger: 'change' }
        ],
        isRefuseReports: [{ required: true, type: 'number', trigger: 'change' }]
      },
      approvalInfoModal: {
        show: false,
        title: '描述',
        content: ''
      }
    };
  },
  computed: {
    checkStatusArr() {
      return Object.values(this.checkStatusObj);
    }
  },
  mounted() {
    this._query = { ...this.query };
    this._formValidate = { ...this.formValidate };
    this.getDeclareCompanyList();
    this.getAccessGrouplist();
    this.refresh();
  },
  methods: {
    prevImg(e) {
      this.$refs.imgView.showModal(e.target);
    },
    showDrawer(sceneId, projectId) {
      this.drawer = true;
      this.sceneId = sceneId;
      this.projectId = projectId;
      this.getDeclareCompanyList();
      this.getAccessGrouplist();
      this.refresh();
    },
    queryDeclareTargetList() {
      // this.query.pageSize = this.calcPageSize();
      queryDeclareTargetList(this.sceneId, this.query)
        .then(({ code, data, messge }) => {
          if (code === 1) {
            let dataList = data.items;
            this.dataList = dataList.map((item) => {
              return {
                ...item,
                opinion: item.opinion || '-',
                descrition: item.descrition || '-',
                url: item.url || '-',
                ip: item.ip || '-'
              };
            });
            this.total = data.total;
          } else {
            this.$Message.error(message);
          }
        })
        .catch((error) => {});
    },
    calcPageSize() {
      return Math.floor((window.innerHeight - 40 - 64) / 37);
    },
    changeCheckStatus(status) {
      this.formValidate.basicScore = 0;
      this.formValidate.isRefuseReports = 1;
    },
    changePage(page) {
      this.query.pageIndex = page;
      this.queryDeclareTargetList();
    },
    refresh() {
      this.query = { ...this._query, pageSize: this.query.pageSize };
      this.changePage(1);
    },
    checkDeclareTarget() {
      this.checkModal.loading = true;
      this.$refs.formValidate.validate(async (valid) => {
        if (valid) {
          if (this.formValidate.isRefuseReports == 1 && this.formValidate.checkStatus == 3) {
            //驳回靶标所有报告
            await this.rejectTargetReports(this.checkModal.data.targetId);
          }
          checkDeclareTarget(
            this.checkModal.data.id,
            this.formValidate.checkStatus,
            {
              basicScore: this.formValidate.basicScore
            },
            { opinion: this.formValidate.opinion }
          )
            .then(({ code, message }) => {
              if (code === 1) {
                this.$Message.info('审核成功');
                this.queryDeclareTargetList();
                this.checkModal.show = false;
              } else {
                this.$Message.error(message);
              }
              this.checkModal.loading = false;
            })
            .catch((error) => {
              this.checkModal.loading = false;
              console.log(error);
            });
        }
        this.checkModal.loading = false;
      });
    },
    //查询靶标报告是否都为驳回状态
    getTargetReportsStatus(targetId) {
      return new Promise((resolve, reject) => {
        getTargetReportsStatus(this.sceneId, targetId)
          .then((res) => {
            let { code, data, message } = res.data;
            if (code === 1) {
              resolve(data);
            } else {
              this.$Message.error(message);
              resolve(false);
            }
          })
          .catch((error) => {
            console.log(error);
            resolve(false);
          });
      });
    },
    // 驳回靶标所有报告
    rejectTargetReports(targetId) {
      return new Promise((resolve, reject) => {
        rejectTargetReports(this.sceneId, targetId)
          .then((res) => {
            let { code, data, message } = res.data;
            if (code === 1) {
              console.log('驳回所有报告');
              resolve();
            } else {
              this.$Message.error(message);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    cancelLoading() {
      this.checkModal.loading = false;
      setTimeout(() => {
        this.checkModal.loading = true;
      });
    },
    getAccessGrouplist() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        testId: this.sceneId
      };
      getaccessgrouplist(params)
        .then(({ code, data, message }) => {
          if (code === 1) {
            let list = data.items;
            this.groupList = list.filter((item) => item.creatorName !== '内部服务用户') || [];
          } else {
            this.$Message.error(message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getDeclareCompanyList() {
      getDeclareCompanyList(this.projectId)
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.companyList = data;
          } else {
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }
  }
};
</script>
<style scoped>
.declare-page{
  /* display: flex;
  flex-direction: column;
  overflow: auto;
  height: calc(100% - 80px);
  padding: 0 20px; */
}
.search-wrapper {
  margin: 15px 0;
  display: flex;
  justify-content: flex-end;
}
/deep/ .search-wrapper > *:not(:nth-child(1)) {
  margin-left: 10px;
}
/deep/ .search-wrapper .ivu-select {
  width: 150px;
}
.declare-drawer /deep/ .ivu-drawer-body {
  overflow: visible;
}
.flex-auto {
  flex: auto;
}
.page-wrapper {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}
</style>
<style>
.html-content {
  word-break: break-all;
}
.html-content img {
  max-width: 100%;
  cursor: pointer;
}
.html-content pre {
  white-space: normal;
}
</style>
